# build in python3.5.2
# 作者：陈常鸿
# 由于虚拟币交易为24h T+0交易，感觉开盘价和闭盘价没有多大作用，只留下最高价线和最低价线
# 布林指标，中间线为前n天的均线，上线=均线+2*（sum(单价-均价)^2)/n，下线=均线-2*（sum(单价-均价)^2)/n
import requests
import matplotlib.pyplot as plt
import numpy as np

K_line=lambda url,token,sec,hour:requests.get(url+token+'?group_sec='+str(sec)+'&range_hour='+str(hour)).json()
result=K_line('https://data.gateio.io/api2/1/candlestick2/','btc_usdt',60,4)['data']
high=[]
low=[]
time=[]
n=0
# (时间，开盘，收盘，最高，最低)
for i in result:
    high.append([float(i[3])])
    low.append([float(i[4])])
    time.append(n)
    n += 1

# 均线
X=np.asarray(time)
highest=np.asarray(high)
lowest=np.asarray(low)
mean=np.add(lowest,highest)/2   # numpy的矩阵可以直接除2，list结构不可以直接除

mean_line=[]
N=int(input("输入n均线的n :"))
for j in range(1,n+1):
    if j<(N+1):
        mean_line.append(np.sum(mean[:j])/j)
    else:
        mean_line.append(np.sum(mean[j-N:j])/N)

# 标准差
stander_error=[]
for k in range(n):
    stander_error.append(16*np.sum(np.sqrt(np.square(mean[k]-mean_line[k]))))
stander_error=np.asarray(stander_error)/n

up_line=[]
down_line=[]
for p in range(n):
    up_line.append(mean_line[p]+stander_error[p])
    down_line.append(mean_line[p]-stander_error[p])

plt.figure()
plt.plot(X,highest,color='black',label='high')
plt.plot(X,mean_line,color='blue',label='mean_line')
plt.plot(X,up_line,color='red',label='up_line')
plt.plot(X,down_line,color='green',label='down_line')
plt.title('BOLL-LINE')
plt.legend()
plt.show()